#include "fatfs.h"
#include "log.h"

#define MAX_LOG_FILE_CNT 100U

static char st_log_file_name[16];
static FIL st_log_file;

uint8_t log_write_to_file(Log_IO_Drv *thiz, uint8_t *buf, uint32_t len, uint32_t timeout);

Log_IO_Drv st_file_io = {
    0,
    LOG_IO_FILE,
    LOG_OK,
    log_write_to_file
};

static char st_log_file_name[16U];
static FIL st_log_file;
static FRESULT st_log_file_status;

__STATIC_INLINE uint8_t _log_file_resume() {
    st_log_file_status = f_close(&st_log_file);
    assert_param(st_log_file_status == FR_OK);
    st_log_file_status = f_open(&st_log_file, st_log_file_name, FA_OPEN_EXISTING | FA_WRITE | FA_READ);
    assert_param(st_log_file_status == FR_OK);
    return st_log_file_status;
}


void log_auto_create_file(){
    for(uint8_t i = 0U; i < MAX_LOG_FILE_CNT; i++) {
        st_log_file_status = f_open(&st_log_file, st_log_file_name, FA_OPEN_EXISTING);
        if(st_log_file_status != FR_OK) {
            sprintf(st_log_file_name, "log_%u.txt", i);
            st_log_file_status = f_open(&st_log_file, st_log_file_name, FA_CREATE_NEW | FA_WRITE | FA_READ);
            assert_param(st_log_file_status == FR_OK);
            return;
        }
        f_close(&st_log_file);
        assert_param(st_log_file_status == FR_OK);
    }
}

uint8_t log_write_to_file(Log_IO_Drv *thiz, uint8_t *buf, uint32_t len, uint32_t timeout) {
    resume:
    st_log_file_status = f_lseek(&st_log_file, st_log_file.fsize);
    assert_param(st_log_file_status == FR_OK);
    uint32_t done;
    st_log_file_status = f_write(&st_log_file, buf, len, &done);
    if(st_log_file_status != FR_OK) {
        _log_file_resume();
        goto resume;
    }
    assert_param(st_log_file_status == FR_OK);
    st_log_file_status = f_sync(&st_log_file);
    assert_param(st_log_file_status == FR_OK);
    return st_log_file_status;
}
